package com.jj.aspect;

import com.jj.annotation.LogAnnotation;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

@Aspect
@Component
public class DemoAspect02 {


    @Pointcut(value = "@annotation(com.jj.annotation.LogAnnotation)")
    private void pointCut() {
    }


    @Before("pointCut()")
    public void beforeAddUser(JoinPoint joinPoint) {
        Object[] args = joinPoint.getArgs();
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        LogAnnotation annotation = method.getAnnotation(LogAnnotation.class);
        String str = annotation.value();


        System.out.println("前置处理: " + args.toString());

    }


    @Around("pointCut()")
    public String aroundAddUser(ProceedingJoinPoint joinPoint) throws Throwable {
        Object[] args = joinPoint.getArgs();
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        LogAnnotation annotation = method.getAnnotation(LogAnnotation.class);
        String str = annotation.value();

        for (Object o : args) {
            if (o instanceof String) {
                System.out.println(o + "，Around");
            }
        }


        Object proceed = joinPoint.proceed();

        System.out.println("环绕处理: " + str);
        str = str + "+环绕处理";
        return proceed + str;
    }

    @After("pointCut()")
    public void afterAddUser(JoinPoint joinPoint) {
        Object[] args = joinPoint.getArgs();
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        LogAnnotation annotation = method.getAnnotation(LogAnnotation.class);
        String str = annotation.value();

        //

        System.out.println("后置处理: " + args[0].toString());

    }

    // @AfterReturning 拦截 getUserById 方法，并获取返回值
    @AfterReturning(value = "pointCut()", returning = "result")
    public void afterReturning(JoinPoint joinPoint, Object result) {
        // result 参数就是目标方法的返回值
        System.out.println("User returned: " + result);



    }

}









